const experss = require("express");
const bodyParser=require("body-parser");
const cookieParser = require("cookie-parser");
const cookieSession =require("cookie-session");
const multer = require("multer");


const db =require("./libs/DBhelper");

let server = experss();

server.use(bodyParser.urlencoded({
    extended:false,
    limit:"200mb"
}));

server.use(bodyParser.json());
server.use(cookieParser("cookier.cn"));
server.use(cookieSession({
    name:"cookier.cn",
    keys:["aaa","bbb","ccc"],
    maxAge:1000*60*20
}))

var multerObj = multer({
    dest: ",.public/upload"
});


server,use(multerObj.any());//所有的请求都支持图片上传

//所有的请求,都会先经过*
server.all("*",(request,response,next)=>{
    //2.准备sql语句
    let sql ="SELECT u_name FROM `userinfo` WHERE u_name= ? AND u_pwd= ?"

    //3.准备参数
    //get请求 request.query
    //post请求 requset.body

    let prames = [request.body.uname,request.body.upwd];
    db.exec(sql,prames,function(err,result,fields){
        if(err){
            response.json({
                msg:"执行sql语句错误",
                err:err.message
            });已经存在就是false
            return;
        }
        if(result.length==1){
            response.json({
                msg:"登录成功",
                status: 1,
                data:result[0]
            });
        }else{
            response.json({
                msg:"登录失败",
                status:-2,
            });
        }
    });
});

//查询

//注册
server .post("/reg",(request,response,next)=>{
    var userObj=request.body;

    let sql =" INSERT INTO `userinfo` (`u_name`,`u_sex`,u_sex);";

    let parmas = [userObj.uname,userObj.upwd,userObj.usex]

    db.exec(sql,parmas,(err,result,fields)=>{
        if(err){
            response.json({
                msg: "执行sql语句错误",
                err:err.message
            });
            return;
        }

        if(result.affectedRows == 1){
            response.json({
                msg:"恭喜,注册成功!",
                status:-2
            });
        }else{
            response.json({
                msg:"注册失败",
                status:-2
            })
        }
        response.end();
    })
})

//校检用户名是否存在

server.get("/checkUname",(request,response,next)=>{
    //1.接收get请求的参数
    var userObj =result.query;

    //2. 准备参数

    let parmas = [userObj.uname];

    //4.执行sql语句,并的到结果,进行判断
    db.exec(sql,parmas,(err,result,fields)=>{
        if(err){
            response.json({
                msg:"执行sql语句错误",
                err:err.message
            });
            return;
        }
        if(result.length==1){
            response.end("false");
        }else{
            response.end("true");
        }
    })
})

//设置端口
server.listen(8081,()=>{
    Console.log("服务器启动完毕")
})